package com.tebiecloud.order.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tebiecloud.common.utils.RedisUtils;
import com.tebiecloud.order.client.constatns.OrderConstants;
import com.tebiecloud.order.client.model.entity.OrderStats1;
import com.tebiecloud.order.server.mapper.OrderStats1Mapper;
import com.tebiecloud.order.server.service.OrderStats1Service;
import com.tebiecloud.common.mybatis.base.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单统计，维度：门店，手机 服务实现类
 * @author tebie
 * @date 2019-09-15
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrderStats1ServiceImpl extends BaseServiceImpl<OrderStats1Mapper, OrderStats1> implements OrderStats1Service {

    @Autowired
    OrderStats1Mapper orderStats1Mapper;

    @Autowired
    RedisUtils redisUtils;

    @Override
    public OrderStats1 createOrUpdate(String unionid, long userId, long storeId, String nickname,String headimgurl,
                                      String phone, int amount, int waitAmount) {

        int time = 10;
        String key = OrderConstants.REDIS_ORDERSTATS2_+storeId+userId;
        boolean isLock = redisUtils.lock(key, time);
        if(!isLock){
            throw new RuntimeException("收益记录被占用，请稍等");
        }
        //查询会员
        QueryWrapper<OrderStats1> orderStats1QueryWrapper = new QueryWrapper<>();
        orderStats1QueryWrapper.eq("user_id",userId);
        orderStats1QueryWrapper.eq("store_id",storeId);
        OrderStats1 orderStats1 = orderStats1Mapper.selectOne(orderStats1QueryWrapper);
        if(orderStats1!=null){
            UpdateWrapper<OrderStats1> orderStats1UpdateWrapper = new UpdateWrapper<>();
            orderStats1UpdateWrapper.eq("user_id",userId);
            orderStats1UpdateWrapper.eq("store_id",storeId);
            OrderStats1 orderStats11 = new OrderStats1();
            orderStats11.setWaitAmount(orderStats1.getWaitAmount() + waitAmount);
            orderStats11.setAmount(orderStats1.getAmount() + amount);
            orderStats1Mapper.update(orderStats11,orderStats1UpdateWrapper);
        }else{
            orderStats1 = new OrderStats1();
            orderStats1.setRemarkName("");
            orderStats1.setAmount(amount);
            orderStats1.setHeadimgurl(headimgurl);
            orderStats1.setNickname(nickname);
            orderStats1.setPhone(phone);
            orderStats1.setStoreId(storeId);
            orderStats1.setUnionid(unionid);
            orderStats1.setWaitAmount(waitAmount);
            orderStats1.setUserId(userId);
            orderStats1Mapper.insert(orderStats1);
        }
        //解锁
        redisUtils.unLock(key);
        return orderStats1;
    }
}
